package org.west.sky.scripture.imports.core.lock;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.west.sky.scripture.imports.core.base.SpringBeanUtil;

import java.time.Duration;
import java.util.Set;

@Slf4j
public class LockUtil {

    private static final StringRedisTemplate redisTemplate;

    private static final String DEFAULT_VALUE = "-";

    private static final String KEY_PREFIX = "lock:import:";

    static {
        redisTemplate = SpringBeanUtil.getBean(StringRedisTemplate.class);
    }


    public static boolean tryLock(String key, long seconds) {
        return tryLock(key, DEFAULT_VALUE, seconds);
    }

    public static boolean tryLock(String key, String value, long seconds) {
        Boolean absent = redisTemplate.opsForValue().setIfAbsent(formatKey(key), value, Duration.ofSeconds(seconds));
        return absent == null || !absent;
    }

    public static boolean releaseLock(String key) {
        String value = redisTemplate.opsForValue().get(formatKey(key));
        Boolean delete = redisTemplate.delete(formatKey(key));
        if (value != null && !DEFAULT_VALUE.equals(value)) {
            return releaseLock(value);
        }
        return delete == null || delete;
    }

    public static void releaseAllLock() {
        Set<String> keys = redisTemplate.keys(KEY_PREFIX + "*");
        if (keys != null) {
            keys.forEach(key -> {
                log.info("正在释放锁：" + key);
                redisTemplate.delete(key);
            });
        }
    }

    private static String formatKey(String key) {
        return KEY_PREFIX + key;
    }
}
